/**
 * @Author: easten
 * @Created: 2024-07-30 16:36:40
 * @Description: 设施设计期
 *
 */
/**
 * @Author: easten
 * @Created: 2024-04-15 23:48:14
 * @Description:
 *
 */
import { DrawerProps } from "_common/DataType";
import { AxiosInstance } from "axios";
import React, { useEffect, useState } from "react";
import { Drawer, MessagePlugin } from "tdesign-react";
import { DesignerInstance, IotDesigner } from "../designer";
import { IotFacility } from "_common/entity";
import "./FacilityDesigner.less";
import { ApiDeviceGroup, ApiFacility } from "_common/api/iot";
type FacilityDesignerProps = DrawerProps & {
  axios: AxiosInstance;
  facility?: IotFacility;
};
const FacilityDesigner: React.FC<FacilityDesignerProps> = (
  props: FacilityDesignerProps
) => {
  const { open, onSuccess, facility, axios } = props;
  const [productCodes, setProductCodes] = useState<number[]>([]);

  const designerRef = React.useRef<DesignerInstance>(null);
  const apiFacility = new ApiFacility(axios);
  const apiProduct = new ApiDeviceGroup(axios);

  useEffect(() => {
    if (!facility) return;
    if (!open) {
      designerRef.current?.destroy();
      return;
    }
    if (
      facility.designerJson &&
      facility.designerJson !== "" &&
      designerRef.current
    ) {
      setTimeout(() => {
        designerRef.current?.load(facility.designerJson!);
      }, 1000);
      setTimeout(() => {
        designerRef.current?.load(facility.designerJson!);
      }, 1000);
    } else {
      designerRef.current?.create(facility.name, facility.id.toString());
    }
    apiProduct.getDeviceGroupList().then((res) => {
      if (res && res.code == 200 && res.data) {
        // res.data
        setProductCodes(res.data?.map((a) => a.groupCode!));
      }
    });
  }, [facility, open]);

  const handleClose = () => {
    onSuccess?.(false);
  };

  return (
    <Drawer
      // header={`设施场景设计 - ${facility?.name}`}
      header={false}
      footer={false}
      visible={open}
      sizeDraggable={false}
      className="designer-drawer"
      size="100%"
      onClose={handleClose}
    >
      <IotDesigner
        axios={axios}
        facilityId={facility?.id}
        ref={designerRef}
        productCodes={productCodes}
        onSave={async (_id, json) => {
          const response = await apiFacility.updateDesignJson({
            facilityId: facility?.id,
            designerJson: json,
          });
          if (response && response.code == 200 && response.data) {
            MessagePlugin.success("保存成功");
          }
        }}
        onExport={async (_id, json) => {
          const blob = new Blob([json], { type: "application/json" });
          const url = URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = `${facility?.name}-场景设计.json`;
          a.click();
          URL.revokeObjectURL(url);
        }}
      />
    </Drawer>
  );
};
export default FacilityDesigner;
